import socket
import threading
import ctypes
import numpy as np
import configparser


ini_file_path = './config.ini'

chn_count = 6
snapshots = 1024
BUFFER_SIZE = 2 * chn_count * snapshots  # 2 bytes per int16, 6 rows, 1024 columns

class mydoaconfig:
    def __init__(self):
        self.IP = "127.0.0.1"
        self.PORT = 12345
        
        self.POWER = 4
        self.ELEMENTCNT = 6
        self.ARRAYTYPE = 'ULA'
        self.SPACING = 6.25
        self.FREQUENCE = 2.4
        

    def __init__(self,configfile):
        config = configparser.ConfigParser()
        # Read the .ini file
        with open(ini_file_path, 'r') as configfile:
            config.read_file(configfile)
        # Access the values
        self.IP = config.get('config', 'IP')
        self.PORT = int(config.get('config', 'Port'))

        self.POWER = 4
        self.ELEMENTCNT = 6
        self.ARRAYTYPE = 'ULA'
        self.SPACING = 6.25
        self.FREQUENCE = 2.4

    def __str__(self):
        return (
                "IP: {}; \
                PORT: {}; \
                POWER: {}; \
                ELEMENTCNT: {}; \
                ARRAYTYPE: {}; \
                SPACING: {}; \
                FREQUENCE: {}; \
                ".format(\
                self.IP, \
                self.PORT, \
                self.POWER, \
                self.ELEMENTCNT, \
                self.ARRAYTYPE, \
                self.SPACING, \
                self.FREQUENCE \
                
                         
                )
                )


def parse_data(data):
    # Create a 2D array of int16 values
    int16_array_6x1024 = ctypes.c_int16 * (6 * 1024)
    parsed_data = ctypes.cast(data, ctypes.POINTER(int16_array_6x1024)).contents
    np_data = np.frombuffer(parsed_data, dtype=np.int16).reshape((6, 1024))
    return np_data

def doaest(np_data):
    print("doaest")

def handle_client(sock, addr):
    print(f"Connection from {addr}")
    while(1):
        data = sock.recv(BUFFER_SIZE)
        if not data:
            break 
        np_data = parse_data(data)
        print(np_data)
        doaest(np_data)

    # Send response back to the client if needed
    # ...
    sock.close()

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    doaconfig = mydoaconfig(ini_file_path)
    print(doaconfig)

    server_socket.bind((doaconfig.IP, doaconfig.PORT))
    server_socket.listen(5)
    print("Server listening...")

    while True:
        client_socket, address = server_socket.accept()
        thread = threading.Thread(target=handle_client, args=(client_socket, address))
        thread.start()

if __name__ == "__main__":
    main()
